C:\jhtp_10th\ch07\fig07_05>java SumArray Total of array elements: loop1 849 loop2 849
SumArray.java// Fig. 7.5: SumArray.java
// Computing the sum of the elements of an array.
public class SumArray
{
public static void main(String[] args)
{
int[] array = {87, 68, 94, 100, 83, 78, 85, 91, 76, 87};
int total1 = 0, total2 = 0;
// add each element's value to total
for (int counter = 0; counter < array.length; counter++)
total1 += array[counter];
// alternative to the for loop above
for (int value: array)
total2 += value;
System.out.printf("Total of array elements: loop1 %d loop2 %d %n", total1,total2);
}
} // end class SumArray
Maintained by John Loomis, updated Tue Jan 24 15:49:48 2017